/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* fac(vector<int>& preorder, vector<int>& inorder,int& preo,
            int inleft,int inright)
        {
            if(inleft>inright)
            {
                return NULL;
            }

            TreeNode* root=new TreeNode(preorder[preo]);
            int inroot=inleft;
            while(inroot<=inright)
            {
                if(inorder[inroot]==preorder[preo])
                    break;
                
                inroot++;
            }// [inleft,inroot-1]   inroot  [inroot+1,inright] 
            preo++;

            root->left=fac(preorder,inorder,preo,inleft,inroot-1);
            root->right=fac(preorder,inorder,preo,inroot+1,inright);
            return root;
        }
    
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int preo=0;
        return fac(preorder,inorder,preo,0,inorder.size()-1);
    }
};
